// 声明一个数组，专门保存todolist数据
var todolist = localStorage.todolist?JSON.parse(localStorage.todolist) : [];
render(todolist);
// 完成输入功能
var input = document.querySelector('#input');
// 监听输入事件
// input.oninput = function(e){
//     console.log(e);
// }

// 监听回车按键
input.onkeydown = function(e){
    // console.log(e);
    if(e.key == 'Enter'){
        // 获取输入框内容，添加到todolist中
        todolist.push({"isDone":false,"content":input.value})
        render(todolist);
        input.value = '';
    }
}


function render(todolist){
    localStorage.todolist = JSON.stringify(todolist);
    var doneDiv = document.querySelector('.done .list');
    var doingDiv = document.querySelector('.doing .list');
    var doneNumSpan = document.querySelector('.done .num');
    var doingNumSpan = document.querySelector('.doing .num');
    doingDiv.innerHTML = "";
    doneDiv.innerHTML ="";
    var doingNum = 0;
    var doneNum = 0;
    todolist.forEach(function(item,i){
        // 根据当前是否完成，觉得渲染到什么位置
        if(item.isDone){
            var div = document.createElement('div');
            div.className = 'item';
            // 多行字符串，可以使用反引号，可以在字符串当中插入变量
            div.innerHTML = `
            <input checked type="checkbox" data-index="${i}">
            <span class="content">${item.content}</span>
            <button class="del" data-index="${i}">删除</button>`;
            doneDiv.appendChild(div);
            doneNum++;
            doneNumSpan.innerHTML = doneNum;
        }else{
            var div = document.createElement('div');
            div.className = 'item';
            div.innerHTML = `
            <input type="checkbox" data-index="${i}">
            <span class="content">${item.content}</span>
            <button class="del" data-index="${i}">删除</button>`;;
            doingDiv.appendChild(div);
            doingNum++;
            doingNumSpan.innerHTML = doingNum;
        }
    })
}


var body = document.body;
body.onchange = function(e){
    // console.log(e);
    // 判断只有复选框的change事件才会执行
    if(e.target.getAttribute('type') == 'checkbox'){
        console.log('只有checkbox才触发');
        var index = e.target.dataset.index;
        todolist[index].isDone = !todolist[index].isDone;
        render(todolist);
    }
}

body.onclick = function(e){
    if(e.target.getAttribute('class') == "del"){
        var index = e.target.dataset.index;
        todolist.splice(index,1);
        render(todolist);
    }
}